//package javabasics;
//
//package org.jasig.cas.integration.restlet;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//import eu.bitwalker.useragentutils.UserAgent;
//import org.jasig.cas.authentication.AESCodec;
//import org.jasig.cas.authentication.LoginLogger;
//import org.jasig.cas.authentication.UcAuthenticationManager;
//import org.jasig.cas.authentication.UcTicketGenerator;
//import org.jasig.cas.authentication.exception.*;
//import org.jasig.cas.authentication.handler.support.EncryptManager;
//import org.jasig.cas.authentication.handler.support.RsaKey;
//import org.jasig.cas.authentication.principal.UserCenterCredentials;
//import org.jasig.cas.integration.util.CaptchaValidateHandler;
//import org.jasig.cas.ticket.InvalidTicketException;
//import org.jasig.cas.ticket.TicketCreationException;
//import org.jasig.cas.ticket.TicketException;
//import org.jasig.cas.util.RedisManager;
//import org.restlet.Context;
//import org.restlet.data.*;
//import org.restlet.resource.Representation;
//import org.restlet.resource.ResourceException;
//import org.springframework.context.i18n.LocaleContextHolder;
//import org.springframework.util.StringUtils;
//import org.springframework.web.bind.support.WebRequestDataBinder;
//import org.springframework.web.context.request.WebRequest;
//
//import javax.servlet.http.HttpServletRequest;
//import java.net.MalformedURLException;
//import java.security.Principal;
//import java.util.*;
//
///**
// * Created by petzold on 2014/5/15.
// */
//public class ServiceTicketResource extends AbstractResource
//{
//    private EncryptManager encryptManager;
//    private RedisManager redisManager;
//    private CaptchaValidateHandler captchaValidateHandler;
//    private LoginLogger loginLogger;
//    private UcAuthenticationManager ucAuthenticationManager;
//    private UcTicketGenerator ucTicketGenerator;
//
//    @Override
//    MediaType initialize(Context context, Request request, Response response)
//    {
//        return MediaType.TEXT_HTML;
//    }
//
//    public boolean allowPost()
//    {
//        return true;
//    }
//
//    public boolean allowDelete()
//    {
//        return true;
//    }
//
//    public ServiceTicketResource(RedisManager redisManager, LoginLogger loginLogger, UcAuthenticationManager ucAuthenticationManager, AESCodec aesCodec, UcTicketGenerator ucTicketGenerator)
//    {
//        this.redisManager = redisManager;
//        this.loginLogger = loginLogger;
//        this.ucAuthenticationManager = ucAuthenticationManager;
//        this.ucTicketGenerator = ucTicketGenerator;
//        setCodec(aesCodec);
//    }
//
//    public void acceptRepresentation(final Representation entity) throws ResourceException
//    {
//        logger.info("进行登陆操作");
//        long start = System.currentTimeMillis();
//        if (logger.isDebugEnabled())
//        {
//            logger.debug("Obtaining credentials...");
//            logger.debug(getRequest().getEntityAsForm().toString());
//        }
//        UserCenterCredentials c = obtainCredentials();
//        Form form = getRequest().getEntityAsForm();
//        String name = form.getFirstValue("username");
//        String url = getRequest().getReferrerRef().getAuthority();
//        String retUrl = form.getFirstValue("retUrl");
//        String channel = form.getFirstValue("tn");
//        c.setChannel(channel);
//        try
//        {
//            String verifyCode = form.getFirstValue("veritycode");
//            String serviceUrl = form.getFirstValue("service");
//            HttpServletRequest request = getServletRequest();
//            if(captchaValidateHandler.isValid(request,verifyCode))
//            {
//                preapreCredentials(c);
//                logger.info("开始产生ST");
//                long st = System.currentTimeMillis();
//                String ticketGrantingTicketId = ucAuthenticationManager.createTicketGrantingTicket(c);
//                String serviceTicketId = ucAuthenticationManager.grantServiceTicket(ticketGrantingTicketId, serviceUrl);
//                logger.info("ST生成成功，耗时:{}", System.currentTimeMillis() - st);
//                org.jasig.cas.authentication.principal.Principal principal = ucAuthenticationManager.getPrincipalByTgt(ticketGrantingTicketId);
//                writeLog((Long) principal.getAttributes().get("boId"), 1, c);
//                addCookie(ticketGrantingTicketId, ucAuthenticationManager.getUserData(ticketGrantingTicketId));
//                ucTicketGenerator.addUcTk((Long)principal.getAttributes().get("boId"), getServletResponse());
//                getResponse().setLocationRef(new Reference(parseUrl(serviceUrl, retUrl, serviceTicketId)));
//                getResponse().setStatus(Status.REDIRECTION_FOUND);
//            }
//        }
//        catch (WrongVerifyCodeException e)
//        {
//            Reference ref = addQueryParameter(getReference(getRequest()),"error","invaildVerityCode",true);
//            logger.error(name + " 验证码错误 来源 " + url);
//            getResponse().setLocationRef(ref);
//            getResponse().setStatus(Status.REDIRECTION_FOUND);
//            writeLog(null, 2, c);
//        }
//        catch (TicketCreationException e)
//        {
//            String error=null;
//            if(e.getCause() instanceof BadPasswordAuthenticationException)
//            {
//                error ="invaildUserNamePassword";
//                logger.error(name+" 密码错误 来源 "+url);
//            }
//            else if(e.getCause() instanceof UserNotAuthorizeException)
//            {
//                error ="noAuthorize";
//                logger.error(name+" 末授权访问系统 来源 "+url);
//            }
//            else if (e.getCause() instanceof UnknownUsernameAuthenticationException)
//            {
//                error = "invaildUserNamePassword";
//                logger.error(name+" 用户名错误 来源 "+url);
//            }
//            else if (e.getCause() instanceof NeedVerifyCodeException)
//            {
//                error ="needVerityCode";
//                logger.error(name+" 需要验证码 来源 "+url);
//            }
//            else if(e.getCause() instanceof InvaildPasswordNeedVerifyCodeException)
//            {
//                error = "invaildUserNamePasswordNeedVerityCode";
//                logger.error(name+" 密码错误,需提供验证码 来源 "+url);
//            }
//            else if(e.getCause() instanceof UserDisabledAuthenticationException)
//            {
//                error = "userIsDisabled";
//                logger.error(name+" 被禁用 来源 "+url);
//            }
//            else if(e.getCause() instanceof LimitLoginException)
//            {
//                error = "limitLogin";
//                logger.error(name+" 被限制登陆 来源 "+url);
//            }
//            Reference ref = addQueryParameter(getReference(getRequest()), "error", error, true);
//            getResponse().setLocationRef(ref);
//            getResponse().setStatus(Status.REDIRECTION_FOUND);
//        }
//        catch (InvalidTicketException e)
//        {
//            getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND, "TicketGrantingTicket could not be found.");
//            writeLog(null,9,c);
//        }
//        catch (TicketException e)
//        {
//            logger.error(e.getMessage(),e);
//            getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
//            writeLog(null,9,c);
//        }
//        catch (LoginTicketExpireException e)
//        {
//            logger.error(String.format("%s LoginTicket错误 来源 [%s] LoginTicke %s",name,getRequest().getReferrerRef().getAuthority(),e.getMessage()));
//            Reference ref = addQueryParameter(getReference(getRequest()),"error","LoginTicketExpire",true);
//            getResponse().setLocationRef(ref);
//            getResponse().setStatus(Status.REDIRECTION_FOUND);
//            writeLog(null,10,c);
//        }
//        catch (Exception e)
//        {
//            logger.error(e.getMessage(),e);
//            Reference ref = addQueryParameter(getReference(getRequest()),"error",e.getMessage(),true);
//            getResponse().setLocationRef(ref);
//            getResponse().setStatus(Status.REDIRECTION_FOUND);
//            writeLog(null,12,c);
//        }
//        long end = System.currentTimeMillis();
//        logger.info("登陆完毕,调用耗时" + (end - start));
//    }
//
//    private String parseUrl(String service, String retUrl, String serviceTicketId) throws MalformedURLException
//    {
//        boolean c = service.contains("?");
//        if(retUrl == null || retUrl.isEmpty()) return service + (c ? "&" : "?") + "ticket=" + serviceTicketId;
//        return service + (c ? "&" : "?") + "ticket=" + serviceTicketId + "&retUrl=" + retUrl;
//    }
//
//    private void writeLog(Long id, int state, UserCenterCredentials credentials)
//    {
//        UserAgent agent = getUserAgent();
//        loginLogger.writeLog(id, 1, credentials.getUsername(), credentials.getSystemId(), credentials.getChannel(), getClientIp(), agent.getBrowser().getName(), agent.getOperatingSystem().getName(), state);
//    }
//
//    private void preapreCredentials(UserCenterCredentials credentials) throws LoginTicketExpireException
//    {
//        fillCredentials(credentials, 1);
//        if (StringUtils.hasText(credentials.getLoginTicket()) && !credentials.getLoginTicket().equals("null"))
//        {
//            logger.info("开始从Redis获取加密私钥");
//            long start = System.currentTimeMillis();
//            JSONObject jo = redisManager.runScript(s -> JSON.parseObject(s), "getEncKey", Arrays.asList(credentials.getLoginTicket()), new ArrayList<String>());
//            logger.info("Redis返回加密私钥，耗时：{}",System.currentTimeMillis() - start);
//            if (jo == null || jo.isEmpty())
//            {
//                throw new LoginTicketExpireException();
//            }
//            else
//            {
//                logger.info("开始解密密码");
//                credentials.setPassword(encryptManager.decrypt(new RsaKey(jo.getString("m"), jo.getString("e")), credentials.getPassword()));
//                logger.info("完成密码解密，耗时:{}",System.currentTimeMillis() - start);
//            }
//        }
//    }
//    protected UserCenterCredentials obtainCredentials()
//    {
//        UserCenterCredentials c = new UserCenterCredentials();
//        WebRequestDataBinder binder = new WebRequestDataBinder(c);
//        RestletWebRequest webRequest = new RestletWebRequest(getRequest());
//        logger.debug(getRequest().getEntityAsForm().toString());
//        logger.debug("Username from RestletWebRequest: " + webRequest.getParameter("username"));
//        binder.bind(webRequest);
//        return c;
//    }
//
//    private Reference getReference(Request request)
//    {
//        Reference reference = request.getReferrerRef();
//        if (reference == null)
//        {
//            Form form = request.getEntityAsForm();
//            reference = new Reference(form.getFirstValue("login_from"));
//        }
//        return reference;
//    }
//    public void setCaptchaValidateHandler(CaptchaValidateHandler captchaValidateHandler)
//    {
//        this.captchaValidateHandler = captchaValidateHandler;
//    }
//
//    public void setEncryptManager(EncryptManager encryptManager)
//    {
//        this.encryptManager = encryptManager;
//    }
//
//
//    protected class RestletWebRequest implements WebRequest
//    {
//
//        private final Form form;
//
//        private final Request request;
//
//        public RestletWebRequest(final Request request) {
//            this.form = getRequest().getEntityAsForm();
//            this.request = request;
//        }
//
//        public boolean checkNotModified(String s) {
//            return false;
//        }
//
//        public boolean checkNotModified(long lastModifiedTimestamp) {
//            return false;
//        }
//
//        public String getContextPath() {
//            return this.request.getResourceRef().getPath();
//        }
//
//        public String getDescription(boolean includeClientInfo) {
//            return null;
//        }
//
//        public Locale getLocale() {
//            return LocaleContextHolder.getLocale();
//        }
//
//        public String getParameter(String paramName) {
//            return this.form.getFirstValue(paramName);
//        }
//
//        public Map<String, String[]> getParameterMap() {
//            final Map<String, String[]> conversion = new HashMap<String,String[]>();
//
//            for (final Map.Entry<String, String> entry : this.form.getValuesMap().entrySet()) {
//                conversion.put(entry.getKey(), new String[] {entry.getValue()});
//            }
//
//            return conversion;
//        }
//
//        public String[] getParameterValues(String paramName) {
//            return this.form.getValuesArray(paramName);
//        }
//
//        public String getRemoteUser() {
//            return null;
//        }
//
//        public Principal getUserPrincipal() {
//            return null;
//        }
//
//        public boolean isSecure() {
//            return this.request.isConfidential();
//        }
//
//        public boolean isUserInRole(String role) {
//            return false;
//        }
//
//        public Object getAttribute(String name, int scope) {
//            return null;
//        }
//
//        public String[] getAttributeNames(int scope) {
//            return null;
//        }
//
//        public String getSessionId() {
//            return null;
//        }
//
//        public Object getSessionMutex() {
//            return null;
//        }
//
//        public void registerDestructionCallback(String name, Runnable callback,
//                                                int scope) {
//            // nothing to do
//        }
//
//        public void removeAttribute(String name, int scope) {
//            // nothing to do
//        }
//
//        public void setAttribute(String name, Object value, int scope) {
//            // nothing to do
//        }
//
//        public String getHeader(final String s) {
//            return null;  //To change body of implemented methods use File | Settings | File Templates.
//        }
//
//        public String[] getHeaderValues(String s) {
//            return new String[0];  //To change body of implemented methods use File | Settings | File Templates.
//        }
//
//        public Iterator<String> getHeaderNames() {
//            return null;  //To change body of implemented methods use File | Settings | File Templates.
//        }
//
//        public Iterator<String> getParameterNames() {
//            return null;  //To change body of implemented methods use File | Settings | File Templates.
//        }
//
//        public Object resolveReference(String s) {
//            return null;  //To change body of implemented methods use File | Settings | File Templates.
//        }
//    }
//}
